// pages/feedback/index.js
Page({
  data: {
    tabs:[
      {
        id: 0,
        name: "体验问题",
        isActive: true
      },
      {
        id: 1,
        name: "商品、商家投诉",
        isActive: false
      }
    ],
    imagesData:[],
    textVal:""
  },

  upLoadImagesUrl:[],

  handleClick(e){
    // console.log(e);
    const {index} = e.detail;
    let tabs = JSON.parse(JSON.stringify(this.data.tabs));
    tabs.forEach((v,i)=>i === index ? v.isActive=true:v.isActive=false);
    this.setData({
      tabs
    })
  },

  handleAddImg(){
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res)=> {
        this.setData({
          imagesData:[...this.data.imagesData, ...res.tempFilePaths]
        })
      }
    });
  },

  handleDelImage(e){
    const {value} = e.detail;
    const index = this.data.imagesData.indexOf(value);
    // console.log(index);
    let data = this.data.imagesData;
    // console.log(data);
    data.splice(index, 1);
    // console.log(data);
    this.setData({
      imagesData: data
    })
  },

  handleTextInput(e){
    // console.log(e);
    this.setData({
      textVal: e.detail.value
    })
  },

  handleSubmit(e){
    const {textVal, imagesData} = this.data;
    if(!textVal.trim()){
      // 为空，不合法
      wx.showToast({
        title: '您输入的值不合法',
        mask: true,
        icon: "none"
      })
      return;
    }

    wx.showLoading({
      title: '正在上传中...',
      mask: true
    })

    if(imagesData.length !== 0){
          // 不为空，输入合法
    imagesData.forEach((v, i) => {
      wx.uploadFile({
        filePath: v,
        name: 'image',
        url: 'https://media.mogu.com/image/scale?appKey=15m&w=500&h=500&quality=100',
        success:(res)=>{
          // console.log(res);
          const url = JSON.parse(res.data).result.url;
          this.upLoadImagesUrl.push(url);

          // 所有图片上传完毕才触发
          if(i === imagesData.length - 1){
            wx.hideLoading();
            console.log("把文本内容和外网的图片数组了传到后台");
            // 提交成功了
            // 重置页面
            this.setData({
              imagesData:[],
              textVal:""
            });
            // 返回上一个页面
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
    }else{
      wx.hideLoading();
      // 仅仅上传文本
      console.log("只上传了文本");
      wx.navigateBack({
        delta: 1
      })
    }

    

  }
})